package com.sysmanage.etl.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 处理文件上传下载
 * 
 * @author zhou.meng
 */
public class FileManager {
    private static final Log log = LogFactory.getLog(FileManager.class);
    
    /**
     * 文件下载
     * @param file
     * @param response
     * @param request
     */
    public static void download(File file, HttpServletResponse response,HttpServletRequest request) {
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(file);
            String agent = request.getHeader("USER-AGENT");
            request.setAttribute("pragma", "no-cache");
            String codedfilename = file.getName();
            if (null != agent && -1 != agent.indexOf("MSIE")) {
                codedfilename = URLEncoder.encode(file.getName(), "UTF8");
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                codedfilename = "=?UTF-8?B?" + (new String(Base64.encodeBase64(file.getName().getBytes("UTF-8")))) + "?=";
            }
            response.setContentType("application/octet-stream; CHARSET=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
            out = response.getOutputStream();

            byte[] b = new byte[2048];
            int i = 0;
            int j = 0;
            long k = file.length();// 下载文件的总大小
            log.info(k + "");

            while ((i = in.read(b)) > 0) {
                out.write(b, 0, i);
                j += i;
                log.info(j + "");
                if (j == 20480) {
                    // in.reset();
                }
            }
            out.flush();
        } catch (IOException e) {
            log.error("用户取消下载", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("FileInputStream close  error!", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("Outputstream close  error! ", e);
                }
            }
        }
    }
    
    

    /**
     * 下载文件
     * 
     * <pre>
     * @desc
     * @createtime 2012-10-9
     * @modifytime 2012-10-9
     * @author lq
     * @modifyauthor lq
     * @version 0303
     * @filename FileManager.java
     * @param fileName
     * @param response
     * @param request
     * @param filelength
     * </pre>
     */
    public static void download(String fileName, HttpServletResponse response, HttpServletRequest request) {
        File file = new File(getPath() + fileName);
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(file);
            String agent = request.getHeader("USER-AGENT");
            request.setAttribute("pragma", "no-cache");
            String codedfilename = file.getName();
            if (null != agent && -1 != agent.indexOf("MSIE")) {
                codedfilename = URLEncoder.encode(fileName, "UTF8");
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
                codedfilename = "=?UTF-8?B?" + (new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?=";
            }
            response.setContentType("application/octet-stream; CHARSET=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + codedfilename);
            out = response.getOutputStream();
            byte[] b = new byte[2048];
            int i = 0;
            int j = 0;
            long k = file.length();
            log.info(k + "");
            while ((i = in.read(b)) > 0) {
                out.write(b, 0, i);
                j += i;
                log.info(j + "");
            }
            out.flush();
        } catch (IOException e) {
            log.error("用户取消下载", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("FileInputStream close  error!", e);
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("Outputstream close  error! ", e);
                }
            }
        }
    }

    public static String getExtName(String fileName) {
        int index = fileName.lastIndexOf('.');
        if (index < 0) {
            return "";
        }
        return fileName.substring(index + 1);
    }

    /**
     * 获取当前路径
     * 
     * @return
     */
    public static String getPath() {
        return PropertiesUtils.getProperty("upload.file.path") + File.separator;
    }

    /**
     * 删除文件夹下的所有单个文件
     * 
     * @return moduleName
     */
    public static void delFiles(String path) throws IOException {
        File file = new File(path);
        if (!file.exists() || !file.isDirectory()) {
            return;
        }

        File[] list = file.listFiles();
        for (File f : list) {
            if (f.isFile()) {
                f.delete();
            }
        }
    }

}
